<?php

namespace App\Console\Commands\OpenShop;

use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use Illuminate\Console\Command;

class InitOpenShopOrderManagerShopId extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:initOpenShopOrderManagerShopId';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化开店流程负责人汇总表督导对应门店id';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        $count = 0;
        OpenShopMainProcessModel::query()
            ->join('open_shop_order_manager', 'open_shop_order_manager.mainProcessId', '=', 'open_shop_main_process.id')
            ->where('open_shop_order_manager.type', OpenShopOrderManagerModel::MANAGER_TYPE_5) // 督导
            ->where('open_shop_order_manager.orderStatus', OpenShopOrderManagerModel::ORDER_STATUS_NORMAL)// 正常
            ->where('open_shop_order_manager.isDeleted', 0)
            ->select(
                [
                    'open_shop_main_process.id', 'open_shop_main_process.orderNo', 'open_shop_main_process.shopId',
                    'open_shop_order_manager.id as managerId', 'open_shop_order_manager.shopId as managerShopId'
                ]
            )
            ->orderBy('open_shop_main_process.id')
            ->chunk(
                100, function ($item) use (&$count) {
                foreach ($item as $v) {
                    $shopId        = $v->shopId ?? 0;
                    $managerShopId = $v->managerShopId ?? 0;

                    if ($shopId && $shopId != $managerShopId) {

                        dump('开店订单： ' . $v->orderNo . '  门店id：' . $shopId);

                        OpenShopOrderManagerModel::query()
                            ->where('id', $v->managerId)
                            ->update(['shopId' => $shopId]);

                        $count++;
                    }
                }
            }
            );

        dump('本次修改总数： ' . $count);

        return 0;
    }
}
